package com.yygo.websocket;

import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class SystemWebSocketHandler implements WebSocketHandler{

    private static final Set<WebSocketSession> users;
    static{
        users = new HashSet<>();
    }

    public SystemWebSocketHandler(){

    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
            throws Exception {
        users.remove(session);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        if (!users.contains(session)) {
            System.out.println("Server:cennected OK!");
            //session.sendMessage(new TextMessage("welcome to websocket"));
            users.add(session);
        }
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
            throws Exception {
        TextMessage tm = new TextMessage(message.getPayload()+"");
        System.out.println(message.getPayload());
        session.sendMessage(tm);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable)
            throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        users.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 给所有在线用户发送消息
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.isOpen()) {
                try {
                    user.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendMessageToUser(String username,String messageStr) {
        TextMessage message = new TextMessage(messageStr);
        for (WebSocketSession user : users) {
            if (user.getAttributes().get("username").equals(username)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
